<?php
namespace app\admin\controller;
/**
 * #用户管理 微手用户管理控制器
 */
class Weishou extends Common{
    /**
     * 实名认证审核
     * @return [type] [description]
     */
    function certification($keyword='',$range=''){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        $params=[
            'range'=>$range,
            'keyword'=>$keyword,
            'is_certification'=>input('status/s',0),
        ];
        $map=[
            'is_certification'=>['is_certification','>',0]
        ];
        if($params['is_certification']>0){
            $map['is_certification']=$params['is_certification'];
        }
        if(!empty($keyword)){
            $map['name|tel|realName']=['name|tel|realName','like',"%{$keyword}%"];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['cert_stime']=['cert_stime','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['cert_stime']=['cert_stime','>=',$range[0]/1000];
            }
        }
        $options=[
            'field'=>'id,tel,name,realName,IDNum,face_img,re_face_img,man_face,is_certification,cert_stime,cert_etime,cert_remark',
            'order'=>'is_certification,cert_stime desc'
        ];
        $list=model('member')->readAll($map,true,$options);
        $this->assign('list',$list);
        $this->assign('params',json_encode($params));
        return view();
    }
    function certHandle($id=0,$cert_remark='',$is_certification=0){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该项数据不存在');
            }
            $has=model('member')->where(['id'=>$id])->count();
            if(!$has){
                $this->error('该项数据可能已经删除');
            }
            if($has['is_certification']>1){
                $this->error('该条认证记录已经处理过,请勿重复操作');
            }
            $e=model('member')->edit(['id'=>$id,'cert_remark'=>$cert_remark,'is_certification'=>$is_certification]);
            if(!$e){
                $this->error('审核失败');
            }
            $this->success('审核成功');
        }
        
    }
    /**
     * #微手用户列表
     * @return view
     */
    function index($keyword='',$range=''){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        
        $params=[
            'range'=>$range,
            'keyword'=>$keyword,
            'vip_level'=>input('vip_level/s','-1'),
        ];
        $options=[
            'field'=>'id,name,tel,status,s_time,head_img,pid,vip_expire,vip_ratio,coin,money,alipay,vip_level,vip_id,is_agent',
        ];
        $module=model('artmodule')->read(['name'=>'single'],'id');
        $map=['module_id'=>$module['id']];
        if(!empty($keyword)){
            $map['tel|name']=['tel|name','like',"%{$keyword}%"];
        }
        if($params['vip_level']>=0){
            $map['vip_level']=$params['vip_level'];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['s_time']=['s_time','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['s_time']=['s_time','>=',$range[0]/1000];
            }
        }
        $list=model('member')->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);

        $vip=model('vip')->readAll(['status'=>1],0,['field'=>'id,name,level','order'=>'sort'])->toArray();
        array_unshift($vip, ['level'=>-1,'name'=>'全部'], ['id'=>0,'level'=>0,'name'=>'非VIP']);
        $this->assign('vip',json_encode($vip));
        $this->assign('params',json_encode($params));
        //p($list->toArray());
        return view();
    }
    /**
     * #代理用户列表
     * @return view
     */
    function dlulist($keyword='',$range=''){
        if(is_string($range)){
            $range=explode(',', $range);
        }
        
        $params=[
            'range'=>$range,
            'keyword'=>$keyword,
            'vip_level'=>input('vip_level/s','-1'),
        ];
        $options=[
            'field'=>'id,name,tel,status,s_time,head_img,pid,vip_expire,vip_ratio,money,alipay,vip_level,vip_id,is_agent',
        ];
        $module=model('artmodule')->read(['name'=>'single'],'id');
        $map=['module_id'=>$module['id']];
        $map=['is_agent'=>1];
        if(!empty($keyword)){
            $map['tel|name']=['tel|name','like',"%{$keyword}%"];
        }
        if($params['vip_level']>=0){
            $map['vip_level']=$params['vip_level'];
        }
        if(!empty($range)){
            if(count($range)===2){
                $map['s_time']=['s_time','between',[$range[0]/1000,$range[1]/1000+86400]];
            }else{
                $map['s_time']=['s_time','>=',$range[0]/1000];
            }
        }
        $list=model('member')->readAll($map,true,$options)->appends($params);
        $this->assign('list',$list);

        $vip=model('vip')->readAll(['status'=>1],0,['field'=>'id,name,level','order'=>'sort'])->toArray();
        array_unshift($vip, ['level'=>-1,'name'=>'全部'], ['id'=>0,'level'=>0,'name'=>'非VIP']);
        $this->assign('vip',json_encode($vip));
        $this->assign('params',json_encode($params));
        //p($list->toArray());
        return view();
    }


    /**
     * #查看代理下级用户
     * @return view
     */
    public function lowList(){
        // 获取不为代理的直属下级信息
        $user = $this->user;

        $pid=input('pid/s','');
        $options=[
            'field'=>'id,name,tel,status,s_time,head_img,pid,vip_expire,vip_ratio,money,alipay,realname,vip_level,vip_id,is_agent',
        ];
        $module=model('artmodule')->read(['name'=>'single'],'id');
        $map=['module_id'=>$module['id']];
        $map=['is_agent'=>['is_agent','neq',1]];
        $map=['pid'=>$pid];
        $list=model('member')->readAll($map,true,$options);
        $this->assign('list',$list);
        // print_r($list);die;

        $vip=model('vip')->readAll(['status'=>1],0,['field'=>'id,name,level'])->toArray();
        array_unshift($vip, ['level'=>-1,'name'=>'全部'], ['id'=>0,'level'=>0,'name'=>'非VIP']);
        $this->assign('vip',json_encode($vip));
        return view();
    }
    /**
     * #新增、修改用户
     * @return view
     */
    function edit($id=0){
        if(request()->isAjax()||request()->isPost()){
            if($id>0){
                $has=model('member')->where(['id'=>$id])->count();
                if(!$has){
                    $this->error('该用户不存在');
                }
                $data=[
                    'id'=>$id,
                    'name'=>input('name/s'),
                    'status'=>input('status/d',1),
                    'is_agent'=>input('is_agent/d',0),
                    'alipay'=>input('alipay/s'),
                    'remark'=>input('remark/s',''),
                ];
                if(empty($data['name'])){
                    $this->error('昵称不能为空');
                }
                $edit=model('member')->edit($data);
                $this->success('修改成功');die;
            }else{
                $module=model('artmodule')->read(['name'=>'single'],'id');
                $days = 7;
                $data=[
                    'tel'=>input('tel/s'),
                    'name'=>input('name/s'),
                    'status'=>input('status/d',1),
                    'is_agent'=>input('is_agent/d',0),
                    'alipay'=>input('alipay/s'),
                    'remark'=>input('remark/s',''),
                    'module_id'=>$module['id'],
                    'trial_member'=>strtotime("+$days day",strtotime(date("Y-m-d"))),
                ];
                if(empty($data['tel'])){
                    $this->error('手机号码不能为空');
                }
                $hasTel=model('member')->where(['tel'=>$data['tel']])->count();
                if($hasTel){
                    $this->error('该手机号码已经注册过了');
                }
                if(empty($data['name'])){
                    $this->error('昵称不能为空');
                }
                $add=model('member')->add($data);
                $this->success('新增成功');die;
            }
        }
    }
    function editVip($id=0,$vip_id=0){
        if(request()->isAjax()||request()->isPost()){
            if($id<=0){
                $this->error('该用户不存在');
            }
            $user=model('member')->read(['id'=>$id],'id,vip_level,pid,tel');
            if(empty($user)){
                $this->error('该用户不存在');
            }
            $vip_id=input('vip_id/d',0);
            if($vip_id<0){
                $this->error('该VIP级别不存在');
            }elseif($vip_id==0){
                // 强制移除用户VIP
                $res=model('member')->isVip($id,true);
                if($res==0){
                    $this->success('移除VIP成功');die;
                }
                $this->error('移除VIP失败');
            }
            $map=[
                'id'=>$vip_id,
                'status'=>1,
            ];
            $module=model('artmodule')->read(['name'=>'single'],'id');
            if(isset($module['id'])){
                $map['module_id']=$module['id'];
            }
            $has=model('vip')->read($map,'id,name,money,ratio,y,m,d,level');
            if(empty($has)){
                return json('该VIP可能已经关闭',1);
            }
            $user=model('member')->read(['id'=>$id],'id,pid,tel');
            // 增加的时长（单位：s）
            $overTime=addDuration($has['y'],$has['m'],$has['d'],true);
            $time=time();
            // 生成订单
            $number=model('order')->number();
            $data=[
                'uid'=>$id,
                'pid'=>$user['pid'],
                'tel'=>$user['tel'],
                's_time'=>$time,
                'expire_time'=>$time+60*86400, //到期时间2个月
                'number'=>$number,
                'vid'=>$has['id'],
                'vip_level'=>$has['level'],
                'cid'=>0,
                'coupon_money'=>0, //优惠卷低扣金额
                'money'=>$has['money'], //用户付款金额
                'raw_money'=>$has['money'],
                'ratio'=>$has['ratio'],
                'time'=>$overTime,

                'is_admin'=>1, //是否后台订单（不计费，不能拿提成）
                'state'=>1, //付款成功
                'e_time'=>$time, //订单完成时间
            ];
            $add=model('order')->add($data);

            if($add){
                // 订单处理
                $res=model('order')->vipOrderHandle($add);
                if($res){
                    // 此处进行日志写入
                    $this->success('更新VIP成功');die;
                }
            }
            $this->error('更新失败');
        }
    }
    /**
     * 会员启用、隐藏
     * @param  integer $id 用户ID
     * @return [type]      [description]
     */
    function close($id=0){
        if(request()->isAjax()||request()->isPost()){
            $this->superCheck();
            $ids=input('ids/a',[]); // 多项
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $where="";
            if(!empty($ids)){
                $ids=implode(',', $ids);
                $where=" `id` in ({$ids}) ";
            }else{
                $where=" `id`={$id} ";
            }
            $rs=model('member')->close($where,'status',true);
            if($rs){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
    /**
     * 微手会员代理商变化
     * @param  integer $id 用户ID
     * @return [type]      [description]
     */
    function isAgent($id=0){
        if(request()->isAjax()||request()->isPost()){
            $this->superCheck();
            $ids=input('ids/a',[]); // 多项
            if($id<=0&&empty($ids)){
                $this->error(lang('Data does not exist'));
            }
            $where="";
            if(!empty($ids)){
                $ids=implode(',', $ids);
                $where=" `id` in ({$ids}) ";
            }else{
                $where=" `id`={$id} ";
            }
            $pwd = '000000';
            $has=model('member')->read($where,'id,is_agent,status,login_pwd');
            // echo json_encode($has);die;

            if ($has['login_pwd'] == '') {
                $udata = array('is_agent'=>1,'login_pwd'=>encrypt_pwd($pwd));
            }
            else{
                $udata = array('is_agent'=>1);
            }

            // $rs=model('member')->close($where,'is_agent',true);
            if ($has['is_agent'] == 1) {
                $udata['is_agent'] = 0;
                $rs=model('member')->where($where)->update($udata);
            }
            else{
                $rs=model('member')->where($where)->update($udata);
            }
            if($rs){
                $this->success(lang('Successful operation'));
                die;
            }
            $this->error(lang('Failed operation'));
        }
    }
}